var defaultParameter = {
  pageNumber: 1,
  pageSize: 20,
  option:'borrow'
};

var filterParam={

};

function initTable(){

  var columns=[[
   {
                field : 'ck',
                checkbox : true
    },
    {field:'impleProjId',title:'项目id',fitColumns:true,hidden:true,
        // formatter: function(value,row,index){
        //     if(row._parentId==null){
        //         return row.impleProjName;
        //     }else{
        //         return "";
        //     }
        // }
    },
    {field:'impleProjName',title:'实施项目名称',width:$(this).width()*0.1,fitColumns:true
    },
    {field:'projStateName',title:'阶段',width:$(this).width()*0.1,fitColumns:true,
        formatter: function(value,row,index){
            if(row.projectStage!=null){
                return row.projectStage.projStateName;
            }else{
                return "";
            }
        }
        },
//    {field:'stageNode',title:'工作节点', width:$(this).width()*0.1,fitColumns:true,
//          formatter: function(value,row,index){
//          return row.stageNode.nodeName;
//          }
//        },
     {field:'uploadName',title:"文件名称",width:$(this).width()*0.1,fitColumns:true,
         formatter: function(value,row,index){
           if(row.docInfo!=null){
             return row.docInfo.fileName;
           }else{
             return "";
           }

         }
        },
      {field:'fileList',title:"文档列表",width:$(this).width()*0.1,fitColumns:true,
          formatter: function(value,row,index){//只有电子文档才会有uploadInfo，纸质的不会有
              if(row.uploadInfos!=null && row.uploadInfos.length>0){
                  var html="";
                  for(var i=0;i<row.uploadInfos.length;i++){
                      html+="<span><a onclick='downloadFile(\""+row.uploadInfos[i].filePath+"\")'>"+row.uploadInfos[i].uploadName+"</a></span><br>";
                  }
                  return html;
              }else{
                  return "";
              }
          }
      },
    // {field:'filePath',title:"文件路径",width:$(this).width()*0.1,fitColumns:true,
    //   formatter: function(value,row,index){
    //     return row.uploadInfo.filePath;
    //   }
    // },
    {field:'fileAttr',title:'文档属性',width:$(this).width()*0.1,fitColumns:true,
          formatter: function(value,row,index){
            if(row.uploadInfos!=null && row.uploadInfos.length>0) {
              return row.uploadInfos[0].fileAttrName;
            }else{
              return "";
            }
          }
    },
   {field:'fileType',title:'文档类型',width:$(this).width()*0.1,fitColumns:true,
              formatter: function(value,row,index){
                if(row.uploadInfos!=null && row.uploadInfos.length>0) {
                  return row.uploadInfos[0].fileTypeName;
                }else{
                  return "";
                }
              }
   },
    {field:'statusCdName',title:'状态',width:$(this).width()*0.1,fitColumns:true,
        formatter: function(value,row,index) {
            if(row.docInfo!=null) {
                return row.docInfo.statusCdName;
            }else{
                return "";
            }
        }
    },
    {field:'participant',title:'参与人',width:$(this).width()*0.1,fitColumns:true,
      formatter: function(value,row,index) {
        if(row.docInfo!=null) {
          return row.docInfo.participantName;
        }else{
          return "";
        }
      }
    },
    {field:'broker',title:"借阅经手人",width:$(this).width()*0.1,fitColumns:true,
      formatter: function(value,row) {
        if(row.fileBorrow!=null) {
          return row.fileBorrow.outBrokerName;
        }else{
          return "";
        }
      }
    },
    {field:'borrower',title:"借阅人",width:$(this).width()*0.1,fitColumns:true,
      formatter: function(value,row) {
        if(row.fileBorrow!=null) {
          return row.fileBorrow.borrowerName;
        }else{
          return "";
        }
      }
    },
    {field:'description',title:"备注",width:$(this).width()*0.1,fitColumns:true,
      formatter: function(value,row) {
        if(row.fileBorrow!=null) {
          return row.fileBorrow.description;
        }else{
          return "";
        }
      }
    },
    {field:'operation',title:"操作",width:$(this).width()*0.1,
       formatter: function(value,row,index){//纸质文档才有借出归还操作
        if(row.uploadInfos!=null && row.uploadInfos.length>0 && row.uploadInfos[0].fileType==20){
            if(row.docInfo!=null && row.docInfo.statusCd==10){
                return '<a class="edit" href="javascript:void(0)" title="借阅" onclick="updateBorrowModel(\''
                    + index
                    + '\')"> <i class="fa fa-sign-out font-middle"></i></a>';
            }
            if(row.level==3 && row.docInfo!=null && row.docInfo.statusCd==20 && row.fileBorrow!=null){
//                if(com.im.common.staffId==row.fileBorrow.borrower){
                    return '<a class="edit" href="javascript:void(0)" title="归还" onclick="updateReturnModel(\''
                        + index
                        + '\')"> <i class="fa fa-reply font-middle"></i></a>';
//                }
            }else{
                return "";
            }
        }else{
            return "";
        }


      }},
  ]];

  $('#fileInfoList').datagrid({
    url:'/InfoManageWeb/folderManageService/queryProjectStageDocInfo',
      method:'post',
      dataType : 'json',
      contentType: 'application/json',
      // idField:'id',
      // treeField:'projStageClass',
      queryParams:defaultParameter,
      nowrap:false,
      fitColumns:true,
      checkOnSelect:true,
       pagination:true,
      singleSelect:false,
      columns:columns,
      onBeforeLoad : function(param){
       for (var key in param) {
         if(key=="rows"){
           delete param[key];
         }
       }
     },
  loadFilter:function(data,parentId){
        if(data.resultCode!=0){
          toastr.error(data.resultCode);
          return null;
        }else{
          // if(data.result.rows!=null){
          //   for(var i=0;i<data.result.rows.length;i++){
          //     if(data.result.rows[i]._parentId==""){
          //       data.result.rows[i]._parentId=null;
          //     }
          //   }
          // }
          return data.result;
        }
      },
    // onBeforeExpand : function(row) {
    //   // 此处就是异步加载地所在
    //     // 此处就是异步加载地所在
    //     if (row) {
    //         if(row.level=="1"){
    //             filterParam.impleProjId=row.impleProjId;
    //             filterParam.parentId=row.id;
    //             $(this).treegrid('options').queryParams=filterParam;
    //             $(this).treegrid('options').url = '/InfoManageWeb/folderManageService/queryProjectStageForDocInfo'
    //         }
    //         if(row.level=="2"){
    //             filterParam.parentId=row.id;
    //             filterParam.projStageId=row.projStageId;
    //             filterParam.option='borrow';
    //             $(this).treegrid('options').queryParams=filterParam;
    //             $(this).treegrid('options').url = '/InfoManageWeb/folderManageService/queryDocInfoByProjStageId'
    //         }
    //     }
    //   return true;
    // },
      onLoadSuccess:function(data){
          mergeCellsByField('fileInfoList','impleProjName',"projStateName");
      }
  });

    var p = $('#fileInfoList').datagrid('getPager');
    $(p).pagination({
      pageSize: 20,//每页显示的记录条数，默认为10
      pageList: [10,20,30],//可以设置每页记录条数的列表
      beforePageText: '第',//页数文本框前显示的汉字
      afterPageText: '页    共 {pages}  页',
      displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
      onSelectPage:function(pageNumber, pageSize){
     defaultParameter.pageNumber=pageNumber;
     defaultParameter.pageSize=pageSize;
    defaultParameter.projStageId=$('#projectStage').val();
    defaultParameter.impleProjId=$('#belongPlan').val();
    defaultParameter.planProjId=$('#planProjClass').val();
    defaultParameter.fileAttr=$("#fileType").val();
    defaultParameter.orgId=$('#orgId').val();
    // $('#fileInfoList').treegrid('options').url="/InfoManageWeb/folderManageService/queryImplementProjectForDocInfo";
     $('#fileInfoList').datagrid('reload',defaultParameter);
      }
    });
}

function updateBorrowModel(index){
 $('#addEditModal').modal("show");
    var row= $('#fileInfoList').datagrid('getData').rows[index];
 $("#docId").val(row.docInfo.docInfoId);
 $("#fileName").val(row.docInfo.fileName);
}

function downloadFile(path){
    location.href="/FileManageWeb/fileController/downloadFile?fileName="+path;
}

function mergeCellsByField(tableID, fldList,other) {
    var Arr = fldList.split(",");
    var dg = $('#' + tableID);
    var fldName;
    var RowCount = dg.datagrid("getRows").length;
    var span;
    var PerValue = "";
    var CurValue = "";
    var length = Arr.length - 1;
    for (i = length; i >= 0; i--) {
        fldName = Arr[i];
        PerValue = "";
        span = 1;
        for (row = 0; row <= RowCount; row++) {
            if (row == RowCount) {
                CurValue = "";
            }
            else {
                CurValue = dg.datagrid("getRows")[row][fldName];
            }
            if (PerValue === CurValue) {
                span += 1;
            }
            else {
                var index = row - span;
                dg.datagrid('mergeCells', {
                    index: index,
                    field: fldName,
                    rowspan: span,
                    colspan: null
                });
                var name = other.split(",");
                $.each(name,function (i,item){
                    dg.datagrid('mergeCells', {
                        index: index,
                        field: item,
                        rowspan: span,
                        colspan: null
                    });
                });
                span = 1;
                PerValue = CurValue;
            }
        }
    }
}

function updateReturnModel(index){
   var row= $('#fileInfoList').datagrid('getData').rows[index];
   var param={};
   param.docInfoIds=row.docInfo.docInfoId;
   param.fileBorrowIds=row.fileBorrow.fileBorrowId;
//   var url="/folderManageService/updateFileBorrowInfo";
   var url="/folderManageService/updateBatchFileBorrowInfo";
    var client = new com.im.common.ajax();
       var result = client.callAsJson(url,param);
       if(result.resultCode!=0){
         toastr.error(result.resultCode);
       }else{
         queryBorrowInfo();
       }
// $('#returnModal').modal("show");
}

function queryBorrowInfo(){
    defaultParameter.projStageId=$('#projectStage').val();
    defaultParameter.impleProjId=$('#belongPlan').val();
    defaultParameter.planProjId=$('#planProjClass').val();
    defaultParameter.orgId=$('#orgId').val();
    defaultParameter.fileAttr=$("#fileType").val();
    // $("#fileInfoList").treegrid('options').url = '/InfoManageWeb/folderManageService/queryImplementProjectForDocInfo'
    $('#fileInfoList').datagrid('load',defaultParameter);
}

function saveFolderBorrowInfo(){
  var param = {};
  var url="/folderManageService/insertBatchFileBorrowInfo";
  param.docInfoIds=$("#docId").val();
  param.borrowType=10;
  param.outBroker=$("#outBorrowerId").val();
  param.description=$("#description").val();
  param.borrowerId=$("#borrowerId").val();
  var formValidator = $('#folderBorrowForm').data('bootstrapValidator');
  formValidator.options.excluded = [ ':hidden', ':not(:visible)'];
  formValidator.validate();
   var client = new com.im.common.ajax();
    var result = client.callAsJson(url,param);
    if(result.resultCode!=0){
      toastr.error(result.resultCode);
    }else{
      $('#addEditModal').modal('hide');
      queryBorrowInfo();
    }
}

function _callBackOutBorrow(staffId,staffName){
  $("#outBorrowerId").val(staffId);
}

function _callBorrow(staffId,staffName){
    $("#borrowerId").val(staffId);
}


function batchBorrow(){
var rows=$('#fileInfoList').datagrid("getChecked");
if(rows==null || rows==undefined || rows.length==0){
    toastr.error("请选中至少一行记录再借出");
     return ;
}
var docInfoIds="";
for(var i=0;i<rows.length;i++){
  var row=rows[i];
  // if(row._parentId==null){
  //   continue;
  // }
  if(row.uploadInfo==null || row.uploadInfo[0].fileType!=20){
      toastr.error("纸质文档才能借出");
      return ;
  }
  if(row.docInfo==null || row.docInfo.statusCd!=10){
    toastr.error("选中的记录状态不对");
     return ;
  }

   docInfoIds=docInfoIds+row.docInfo.docInfoId+",";
}
if(docInfoIds==""){
  return ;
}
  $('#addEditModal').modal("show");
  $("#docId").val(docInfoIds);

}

function batchReturn(){
var rows=$('#fileInfoList').datagrid("getChecked");
if(rows==null || rows==undefined || rows.length==0){
    toastr.error("请选中至少一行记录再归还");
     return ;
}
var fileBorrowIds="";
var docInfoIds="";
for(var i=0;i<rows.length;i++){
  var row=rows[i];
  if(row._parentId==null){
    continue;
  }
  if(row.docInfo==null || row.docInfo.statusCd!=20){
    toastr.error("选中的记录状态不对");
     return ;
  }

   if(row.fileBorrow==undefined /**|| com.im.common.staffId!=row.fileBorrow.borrower**/){
      toastr.error("选中的记录状态不对");
       return ;
    }
   fileBorrowIds=fileBorrowIds+row.fileBorrow.fileBorrowId+",";
   docInfoIds=docInfoIds+row.docInfo.docInfoId+",";
   }
  if(docInfoIds==""){
    return ;
  }

   var param={};
   param.fileBorrowIds=fileBorrowIds;
   param.docInfoIds=docInfoIds;
      var url="/folderManageService/updateBatchFileBorrowInfo";
       var client = new com.im.common.ajax();
          var result = client.callAsJson(url,param);
          if(result.resultCode!=0){
            toastr.error(result.resultCode);
          }else{
            queryBorrowInfo();
          }

}

function initOrg(){
  var client = new com.im.common.ajax();
  var result = client.callAsJson("userService/queryOrgarizationsByCond", {"forOrgList": "","orgType":10});

  if(!result.success){
    toastr.error(result.resultMsg);
  }else{
    result.result.unshift({'orgId':'','orgName':'全部'});
    $.each( result.result, function (i) {
      $('#orgId').append("<option value=" + result.result[i].orgId + ">" +result.result[i].orgName + "</option>");

    });
    $("#orgId").select2({});
  }
}

function initImplProject(){
  $('#belongPlan').append("<option value=''>全部</option>");
}

$(function() {
//  initOrg();

     $("#orgId").project2unit2itemCommpent({
                  //elmIdProjectSel : "projectSel",//规划工程下拉元素
                  elmIdPlanTypeSel : "planProjClass",
                  elmIdUnitSel : "orgId",//组织单位下拉元素
                  elmIdItemSel : "belongPlan",//实施项目下拉元素
                  orgType : "10",//初始化单位时，单位类型
                  callbackFunc: function (callBackType, ret) {//下拉框值改变时回调
                      //_callBackOrg(objvalue, objname);
                      //callBackType : 1 所属规划值变更 2单位值变更  3项目名称变更
                      //ret: orgId,orgName,impleProjId,impleProjName,planProjClass,planProjClassName
                       queryBorrowInfo();
                  }
              });

  initTable();

  $("#userBtn").click(function() {
    $("#borrower").userSearchCommpent({
      elmIdOut : "borrower",//组织树单击之后回填的文本框（input）
      elmIdModal : "userSearchModal",//用户选择
      elmIdOrgModal : "unitSearchModal",//组织查询
      callbackFunc: function (staffId, staffName) {//组织树单击之后回调函数
        _callBorrow(staffId, staffName);
      }
    });
  });

  $("#userBtn1").click(function() {
    $("#outBorrower").userSearchCommpent({
      elmIdOut : "outBorrower",//组织树单击之后回填的文本框（input）
      elmIdModal : "userSearchModal",//用户选择
      elmIdOrgModal : "unitSearchModal",//组织查询
      callbackFunc: function (staffId, staffName) {//组织树单击之后回调函数
          _callBackOutBorrow(staffId, staffName);
      }
    });
  });

//  $("#planProjClass").constantCommpent({
//    elmIdSel : "planProjClass",//需要展示的位置下拉框
//    constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
//    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
//    }
//  });

  $("#fileType").constantCommpent({
    elmIdSel : "fileType",//需要展示的位置下拉框
    constParamCode : "UPLOAD_FILE_TYPE",//需要加载的常量编码
    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    }
  });

  initImplProject();


    // $("#projectBtn").click(function() {
    //   $("#projectBtn").projectSearchCommpent({
    //     elmIdOut : "projuectOut",//组织树单击之后回填的文本框（input）
    //     elmIdModal : "projectSearchModal",//用户选择
    //     elmIdOrgModal : "unitSearchModal",//组织查询
    //     callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
    //       // _callBackProjectCondition(projectId, projectName);
    //     }
    //   });
    // });

      $("#projectStage").constantCommpent({
        elmIdSel : "projectStage",//需要展示的位置下拉框
        constParamCode : "PRE_WORK_APPROVALl",//需要加载的常量编码
        callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
        }
      });

  $("#ensureBtn").click(function(){
    saveFolderBorrowInfo();
  });

  $("#btn_borrow").click(function(){
    batchBorrow();
  });

    $("#btn_return").click(function(){
      batchReturn();
    });

    $("#vFilesBtn").click(function(){
      queryBorrowInfo();
    });

  $("#folderBorrowForm").bootstrapValidator({
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-loadData'
    },
    excluded: [':hidden', ':not(:visible)'],
    fields: {
      fileName: {
        validators: {
          notEmpty: {
            message: '文档名称不能为空'
          }
        }
      },
      borrowDt: {
        trigger:"change",
        validators: {
          notEmpty: {
            message: '借阅时间不能为空'
          }
        }
      },
//      borrower: {
//        validators: {
//          notEmpty: {
//            message: '借阅人不能为空'
//          }
//        }
//      },
      outBorrower: {
        validators: {
          notEmpty: {
            message: '经手人不能为空'
          }
        }
      },
    }
  });

  $('.datetimepicker').datepicker({
      onSelect:function (){
      	$('.datetimepicker').trigger("change");
      }
  });
});